<template>
  <view class="page-main">
    <view class="current-location">
      <view class="left-text">当前定位: {{address.city || '无'}}</view>
      <view v-if="!located" class="right-text" @click="confirmLocation()">重新定位</view>
      <view v-else class="right-text" @click="confirmLocation()">确认</view>
    </view>
    <view class="location-main">
      
      <view class="hot-city-header">
        <view class="hot-city-title">
          热门城市
        </view>
      </view>
      <view class="hot-city-wrapper">
        <view
            class="hot-city-box" v-for="(cityName, index) in hotCity"
            
            :key="index"
            @click="setCityAndGoToHome(cityName)">{{cityName}}
        
        </view>
      </view>
      
      <!-- list-main-wrapper  START -->
      <view
          class="list-main-wrapper" ref="domCityListsWrapper"
      >
        
        <view class="domItemQ" v-for="(list, idx) in cityLists" :key="idx"
        
        >
          <indexed-list-item class="indexed-list-item listItemQ" :list="list" :loaded="loaded" :idx="idx"
                             @itemClick="setLocation">
          </indexed-list-item>
        </view>
      </view>
      <!-- list-main-wrapper  END -->
      
      <!--   侧边栏 选择部分 -->
      <!-- <view class="uni-indexed-list__menu" id="sideListMain" :class="touchmove ? 'uni-indexed-list__menu--active' : '' "
            @touchstart="touchStart" @touchmove.stop.prevent="touchMove" @touchend="touchEnd">
        <view class="uni-indexed-list__menu-item">
          <text class="uni-indexed-list__menu-text"
                :class="touchmoveIndex === 0 ? 'indexed-list__menu-text--active' : ''">热
          </text>
        </view>
        
        <view v-for="(list, key) in cityLists" :key="key" class="uni-indexed-list__menu-item">
          <text class="uni-indexed-list__menu-text"
                :class="(touchmoveIndex - 1) === key ? 'indexed-list__menu-text--active' : ''">{{ list.key }}
          </text>
        </view>
      </view> -->
    
    
    </view>
    <!--   提醒部分, 显示当前选择的字母   -->
    <view v-if="touchmove" class="select-alert-wrapper">
      <text class="alert-text">
        {{alertText}}
      </text>
    </view>
  </view>
</template>

<script>

import indexedList from '@/components/uni-indexed-list/alpha-indexed-list.vue';
import indexedListItem from '@/components/uni-indexed-list/my-indexed-list-item';
import { appMixin } from '../../util/reuse';
import { d_uniShowToast, MY_LOCATION, TOAST_DURATION } from '../../util/misc';
import { uniRequest } from '../../util/network';
import { proGetLocation, uniGetStorageSync, uniReLaunch } from '../../util/funcs';
import { failCbObject, uniHideLoading, uniShowLoading } from '../../util/commonFuncs';


export default {
    mixins: [appMixin],
    computed: {
      alertText() {
        if (this.touchmoveIndex === 0) {
          return '热'
        } else {
          return this.cityLists[this.touchmoveIndex - 1]?this.cityLists[this.touchmoveIndex - 1].title:[]
        }
      }
    },
    components: {
      indexedList,
      indexedListItem
    },
    data() {
      return {
        address: {},
        located: false,
        totalCity: 0,
        // hotCity: hotCity,
        hotCity: [],
        options: [],
        // options: locationData.list,
        scrollViewId: undefined, // 想滚到的元素位置, 当前方案没有用这个变量
        /** touchmoveIndex 作用:
         * - 右边字母表item是否高亮
         * - 计算弹出框内的字母或'热'字,
         * - 过滤无效的滚动结果
         * */
        touchmoveIndex: -1,
        loaded: false, // 传给子组件indexed-list-item, 用于标志数据加载是否完成
        cityLists: [], // 所有城市列表
        touchmove: false,
        sideBarHeight: 0, // 列表的可视高度
        itemHeight: 0, // 字母的高度
        sideBarOffsetY: 0, // 字母表索引sidebar距离顶部的位置
        arrToScroll: [0],
      };
    },
    methods: {
      confirmLocation() { // 重新定位或确认返回
        if (this.located) {
          this.setCityAndGoToHome(this.address.city)
          return
        }
        proGetLocation(false).then((res) => {
          this.address = res
          d_uniShowToast({
            title: '定位成功, 当前城市为' + this.address.city,
            duration: TOAST_DURATION + 1000
          }, false)
          this.located = true
        }).catch((res)=>{
          console.log('定位失败',res)
        })
      },
      setList() {
        console.log(1)
        this.options.forEach((value, index) => {
          if (value.data.length === 0) {
            return
          }
          let indexBefore = index
          // items: 一个选项列表, 比如字母开头为A的所有城市
          let items = value.data.map(item => {
            let obj = {}
            obj['key'] = value.letter
            obj['name'] = item.name || item
            obj['itemIndex'] = index
            obj['id'] = item.id
            index++
            obj.checked = item.checked ? item.checked : false
            return obj
          })
          // temItem: 一个选项列表, 比如字母开头为A的所有城市
          let temItem = {
            title: value.letter,
            key: value.letter,
            items: items,
            itemIndex: indexBefore
          }
          this.cityLists.push(temItem)
        })
        uni.createSelectorQuery()
            .in(this)
            .select('#sideListMain')
            .boundingClientRect()
            .exec(ret => {
              this.sideBarOffsetY = ret[0].top
              this.sideBarHeight = ret[0].height
              this.itemHeight = this.sideBarHeight / (this.cityLists.length + 1) // 多加1 是因为热门城市占一个
            })

      },
      toMove(index) {
        this.touchmoveIndex = index
        // 只要滚动到正常值才进行真正的滚动, 有可能从热往上滚, 或者z往下滚,
        if (this.touchmoveIndex < 0) {
          this.touchmoveIndex = 0
        } else if (this.touchmoveIndex > this.cityLists.length) {
          this.touchmoveIndex = this.cityLists.length
        } else {
          this.uniScroll(index)

        }
      },
      touchStart(e) {
        this.touchmove = true
        let Y = e.touches[0].clientY
        let index = Math.floor((Y - this.sideBarOffsetY) / this.itemHeight)
        this.toMove(index)
      },
      touchMove(e) {
        let Y = e.touches[0].clientY
        let index = Math.floor((Y - this.sideBarOffsetY) / this.itemHeight)
        if (this.touchmoveIndex === index) {
          return false
        }
        this.toMove(index);
      },
      touchEnd() {
        this.touchmove = false
        this.touchmoveIndex = -1 // 离开右边索引表后, 右边的字母无高亮
      },
      onClick(e) {
        let {
          idx,
          index
        } = e
        let obj = {}
        for (let key in this.cityLists[idx].items[index]) {
          obj[key] = this.cityLists[idx].items[index][key]
        }
        let select = []
        if (this.showSelect) {
          this.cityLists[idx].items[index].checked = !this.cityLists[idx].items[index].checked
          this.cityLists.forEach((value, idx) => {
            value.items.forEach((item, index) => {
              if (item.checked) {
                let obj = {}
                for (let key in this.cityLists[idx].items[index]) {
                  obj[key] = this.cityLists[idx].items[index][key]
                }
                select.push(obj)
              }
            })
          })
        }
        let res = {
          item: obj,
          select: select
        }
        this.$emit('click', res)
        return res
      },
      uniScroll(i) {
        uni.pageScrollTo({
          duration: 0, //过渡时间必须为0，uniapp bug，否则运行到手机会报错
          scrollTop: this.arrToScroll[i],
          success: (res) => {
          },
          fail: (res) => {
          },
        })
      },
      setLocation(sData) {
        let {item} = this.onClick(sData)
        this.setCityAndGoToHome(item.name)
      },
      setCityAndGoToHome(cityName) {
        // let selectedLocation =  {
        //   city: cityName
        // }
        // let storageLocation = uniGetStorageSync(MY_LOCATION)
        // if (selectedLocation.city === storageLocation.city){
        //   selectedLocation = storageLocation
        // }
        
        // uni.setStorageSync(MY_LOCATION,selectedLocation) // 点选城市后, 全局可获取

        uni.setStorageSync(MY_LOCATION, {
          city: cityName
        }) // 点选城市后, 全局可获取

        uniReLaunch('/home/home')
      },

      // 设置可以使用touchmove 索引去的top index, 推进arrToScroll, arrToScroll 给 uniScroll 用于响应用户去要去的字母
      setArrToScroll() {
        const query = uni.createSelectorQuery().in(this);
        query.selectAll('.domItemQ').boundingClientRect(data => {
          data.forEach(item => {
            return this.arrToScroll.push(item.top)
          })
        }).exec();
        uniHideLoading()
      }
    },
    mounted() {
      uniShowLoading('加载中')
      this.address = uniGetStorageSync(MY_LOCATION) || {city: ''}
      
      uniRequest('/region', {},{
        method: 'GET',
        success: ({data}) => {
          if (data.code === 200) {
            this.hotCity = data.data.build_city
            this.options = data.data.region_list

            // 完成请求后 , 设置列表和数组
            setTimeout(() => {
              this.setList()
              this.loaded = true //
            }, 50);
            setTimeout(() => {
              this.setArrToScroll()
            }, 300)

          } else {
            d_uniShowToast({
              title: data.msg
            })
          }
        },
        ...failCbObject()

      })
    },

  };
</script>

<style scoped lang="scss">
  @import "../../assets/styles/global";
  
  .page-main {
    
    overflow-x: hidden;
    
    .select-alert-wrapper {
      @include absCenter;
      position: fixed;
      width: 80px;
      height: 80px;
      border-radius: 80px;
      line-height: 80px;
      font-size: 35px;
      color: #fff;
      background-color: rgba(0, 79, 191, 0.5);
      @include center;
      
      .alert-text {
      }
    }
    
    .current-location {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 7px 17px;
      font-size: 14px;
      box-sizing: border-box;
      height: 11vw;
      width: 100vw;
      background-color: #f7f8fa;
      
      .left-text {
      }
      
      .right-text {
        color: #004fbf;
        &:active{
          color: rgba(0, 102, 253, 0.3);
        }
      }
    }
    
    .location-main {
      // 热门城市开始
      min-height: 100vw;
      
      .alpha-navi-bar {
      }
      
      display: flex;
      flex-direction: column;
      width: 347px;
      box-sizing: border-box;
      
      .hot-city-header {
        height: 45px;
        width: 347px;
        
        .hot-city-title {
          height: 45px;
          left: 7vw;
          position: absolute;
          display: flex;
          align-items: center;
          
          font-size: 12px;
          font-weight: normal;
          font-stretch: normal;
          line-height: 6vw;
          letter-spacing: 0vw;
          color: #969799;
          
          &:before {
            content: " ";
            position: absolute;
            left: -3vw;
            width: 4px;
            height: 10px;
            top: 18px;
            
            background-color: #004fbf;
          }
          
        }
      }
      
      .hot-city-wrapper {
        display: flex;
        /*justify-content: space-between;*/
        flex-direction: row;
        width: 92vw;
        /*background-color: yellow;*/
        flex-wrap: wrap;
        box-sizing: border-box;
        max-height: 165px;
        padding-bottom: 21px;
        padding-left: 5px;
        
        .hot-city-box {
          width: 27vw;
          /*background-color: red;*/
          height: 40px;
          border-radius: 4px;
          border: solid 1px #ebedf0;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          font-weight: normal;
          font-stretch: normal;
          line-height: 24px;
          color: #3d444c;
          margin-left: 10px;
          margin-bottom: 8px;
        }
      }
      
      .list-main-wrapper {
        width: 94vw;
        /*height: 94vw;*/
        
      }
      
      .uni-indexed-list__menu--active {
        background-color: rgba(200, 200, 200, .1);
      }
      
      .uni-indexed-list__menu {
        position: fixed;
        right: 0;
        top: 85px;
        width: 6vw;
        flex-direction: column;
        @include center;
        color: #323233;
        font-size: 12px;
        height: 570px;
        /*background-color: red;*/
        
        .uni-indexed-list__menu-item {
          @include center;
          flex: 1;
        }
        
        .indexed-list__menu-text--active {
          color: rgba(0, 79, 191, .1);
        }
      }
      
      .alpha-indexed-list {
        margin-right: -32px;
      }
    }
  }
</style>
